package com.xiaobawang.hundouluo.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import com.xiaobawang.hundouluo.R;
import com.xiaobawang.hundouluo.service.DataService;
import com.xiaobawang.hundouluo.utils.RefreshableView;

import java.util.ArrayList;
import java.util.List;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 */
public class DataFragment extends Fragment {

    private Spinner spinnerType, spinnerTime;
    private BaseAdapter adapterType, adapterTime;
    private String[] dataType, dataTime, sensorNames;
    private String spinnerTypeChoose;
    private LineChartView lineChart;
    private Button btn;
    private BroadcastReceiver receiver;


    public DataFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //广播接收器的注册
        receiver = new DataReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.xiaobawang.hundouluo.receiver.data.interval");
        DataFragment.this.getContext().registerReceiver(receiver, filter);

        // Inflate the layout for this fragment
        View root =  inflater.inflate(R.layout.fragment_data, container, false);
        btn = root.findViewById(R.id.fragment_data_btn_search);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getDataFromService(sensorNames[spinnerType.getSelectedItemPosition()], dataTime[spinnerTime.getSelectedItemPosition()].substring(0,1));
            }
        });

        //找到控件
        spinnerType = root.findViewById(R.id.fragment_data_spinner_type);
        spinnerTime = root.findViewById(R.id.fragment_data_spinner_time);

        //找出数据源
        dataType = new String[]{"空气温度","土壤湿度","CO₂浓度","光照强度"};
        sensorNames = new String[]{"airTemp", "soilHum", "soilHum", "light"};
        dataTime = new String[]{"1分钟","2分钟","3分钟","4分钟","5分钟"};

        //创建适配器
        adapterType = new ArrayAdapter<String>(DataFragment.this.getContext(), android.R.layout.simple_spinner_dropdown_item, dataType);
        adapterTime = new ArrayAdapter<String>(DataFragment.this.getContext(), android.R.layout.simple_spinner_dropdown_item, dataTime);

        //控件加载适配器
        spinnerType.setAdapter(adapterType);
        spinnerTime.setAdapter(adapterTime);


        lineChart = root.findViewById(R.id.fragment_data_chart);

        getDataFromService(sensorNames[0], dataTime[0].substring(0,1));

        return root;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DataFragment.this.getContext().unregisterReceiver(receiver);
    }

    private void initLineChart(String yName, double[] showData) {
        // X 轴设置
        String[] xStrs = new String[]{"1","2","3","4","5"};
        List<AxisValue> axisXValues = new ArrayList<>();
        for(int i=0;i<xStrs.length;i++){
            axisXValues.add(new AxisValue(i).setLabel(xStrs[i]));
        }
        Axis axisX = new Axis(); //X轴
//        axisX.setHasTiltedLabels(true);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setTextColor(Color.GRAY);  //设置字体颜色
        axisX.setTextSize(12);//设置字体大小
        axisX.setHasLines(true); //x 轴分割
        axisX.setName("时间") ;  // x 轴标题
        axisX.setValues(axisXValues);

        // Y轴设置
        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis();  //Y轴
        int[] num = new int[]{0,10,20,30,40,50,60,70,80,90};
        List<AxisValue> axisYValues = new ArrayList<>();
        for (int i=0;i<num.length;i++){
            axisYValues.add(new AxisValue(i).setValue(num[i]));
        }
        axisY.setValues(axisYValues);
        axisY.setName(yName);//y轴标注
        axisY.setTextSize(12);//设置字体大小

        //图表的数据点

        List<PointValue> mPointValues = new ArrayList<PointValue>();
        for (int i = 0; i < showData.length; i++) {
            mPointValues.add(new PointValue(i, (float) showData[i]));
        }

        // 图标线条设置
        Line line = new Line(mPointValues).setColor(Color.parseColor("#FFCD41"));  //折线的颜色（橙色）
        List<Line> lines = new ArrayList<Line>();
//        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
//        line.setCubic(false);//曲线是否平滑，即是曲线还是折线
//        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(true);//曲线的数据坐标是否加上备注
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);
        data.setAxisXBottom(axisX);
        data.setAxisYLeft(axisY);
        lineChart.setLineChartData(data);
    }

    private void getDataFromService(String sensorName, String interval) {

        Intent sIntent = new Intent(DataFragment.this.getContext(), DataService.class);
        sIntent.putExtra("type", "interval");
        sIntent.putExtra("sensorName", sensorName);
        sIntent.putExtra("interval", interval);
        sIntent.putExtra("rowNum", "5");
        DataFragment.this.getContext().startService(sIntent);

    }

    class DataReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getStringExtra("status").equalsIgnoreCase("success")) {
                String dataUnit = intent.getStringExtra("dataUnit");
                double[] datas = intent.getDoubleArrayExtra("datas");
                String yName = dataType[spinnerType.getSelectedItemPosition()] + "/" + dataUnit;
                initLineChart(yName, datas);
            } else {
                Toast.makeText(DataFragment.this.getContext(), "获取数据失败!请稍后再试", Toast.LENGTH_LONG).show();
            }
        }
    }

}
